local class = require 'hump.class'
require 'utilities.drawable'
local text = require 'utilities.text'
local audio = require 'utilities.audiocache'
local color = require 'utilities.color'

GameClient = class{
  function(self, server, id, ip, port)
    self.running = false
    self.ready = false
    self.id = id
    self.gameover = false
    self.server = server
    self.color = self.server:command('shipNew(\'' .. self.id .. '\')')
  end
}

function GameClient:update(dt)
  self.running = self.server:command('running()')
  if self.running then
    self.ready = self.server:command('shipIsReady(\'' .. self.id .. '\')')
    if self.ready then
      if love.keyboard.isDown('right') then
        self.server:command('shipRotate(\'' .. self.id .. '\', ' .. math.pi .. ', ' .. dt .. ')')
      elseif love.keyboard.isDown('left') then
        self.server:command('shipRotate(\'' .. self.id .. '\', ' .. -math.pi .. ', ' .. dt .. ')')
      end
    
      if love.keyboard.isDown('up') then
        self.server:command('shipAccelerate(\'' .. self.id .. '\', ' .. dt .. ')')
      end
    
      if love.keyboard.isDown(' ') then
        self.server:command('shipShoot(\'' .. self.id .. '\', ' .. dt .. ')')
      end
    else
      if love.keyboard.isDown(' ') then
        self.server:command('shipReady(\'' .. self.id .. '\')')
      end
    end
  
  elseif love.keyboard.isDown('return') then
    self.server:command('reinitialize()')
    self.server:command('shipNew(\'' .. self.id .. '\')')
  elseif love.keyboard.isDown('escape') then
    os.exit()
  end
end

function GameClient:draw()
  local state = self.server:command('state()')
  local bg = state['background']
  Drawable.draw(bg.cx, bg.cy, bg.width, bg.height, bg.rotation, bg.graphics)
  for k,v in pairs(state) do
    if k ~= 'background' then
      Drawable.draw(v.cx, v.cy, v.width, v.height, v.rotation, v.graphics, true)
      audio.play(v.audio)
    end
  end
  
  if not self.running then
    text.drawCenterText('Game over. Press enter to restart or esc to exit.', 0, 12)
  elseif not self.ready then
    text.drawCenterText('Press space to begin...', 0, 12)
  else
    color.setColor(self.color)
    text.drawCenterText(self.color, 0, 12)
    color.setColor('white')
  end
end
